<template>
  <span style="position: relative; float: right; margin-right: 50px">
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" append-to-body>
      <div v-show="operate === 'add'" style="margin-top: 20px">
        <el-radio :label=true v-model="select">添加测试账号</el-radio>
        <el-radio :label=false v-model="select">导入测试账号</el-radio>
      </div>
      <br />
      <br />
      <el-form v-show="select" ref="accountForm" :model="accountForm" :rules="rulesAccountForm" class="accForm">
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item label="是否使用" :label-width="formLabelWidth" prop="flagUsage">
              <el-radio-group v-model="accountForm.flagUsage">
                <el-radio-button :label=true>已使用</el-radio-button>
                <el-radio-button :label=false>未使用</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否持仓" :label-width="formLabelWidth" prop="isHold" style="width: 100%">
              <el-radio-group v-model="accountForm.isHold">
                <el-radio-button :label=true>已持仓</el-radio-button>
                <el-radio-button :label=false>未持仓</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="6">
          <el-col :span="10">
            <el-form-item label="项目" :label-width="formLabelWidth" prop="project">
              <el-input v-model="accountForm.project" autocomplete="off" placeholder="项目名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="环境" :label-width="formLabelWidth" prop="env">
              <el-select style="width:100%"
                v-model="accountForm.env"
                filterable
                allow-create
                default-first-option
                placeholder="请选择环境">
                <el-option
                  v-for="item in envOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="6">
          <el-col :span="10">
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
              <el-input v-model="accountForm.userName" autocomplete="off" placeholder="用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
              <el-input v-model="accountForm.phone" autocomplete="off" placeholder="请输入测试账户手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="6">
          <el-col :span="10">
            <el-form-item label="客户号" :label-width="formLabelWidth" prop="clientId">
              <el-input v-model="accountForm.clientId" autocomplete="off" placeholder="请输入机构方定义的客户ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
              <el-input v-model="accountForm.email" autocomplete="off" placeholder="请输入测试账户邮箱"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="6">
          <el-col :span="8">
            <el-form-item label="登录密码" :label-width="formLabelWidth" prop="loginPassword">
              <el-input v-model="accountForm.loginPassword" autocomplete="off" placeholder="移动端登录密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交易密码" :label-width="formLabelWidth" prop="transPassword">
              <el-input v-model="accountForm.transPassword" autocomplete="off" placeholder="交易密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="验证码" :label-width="formLabelWidth" prop="verifyCode">
              <el-input v-model="accountForm.verifyCode" autocomplete="off" placeholder="登录验证码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="6">
          <el-col :span="8">
            <el-form-item label="账户UID" :label-width="formLabelWidth" prop="raasUid">
              <el-input v-model="accountForm.raasUid" autocomplete="off" placeholder="请输入弘量账户系统UID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户风评" :label-width="formLabelWidth" prop="userRiskType">
              <el-input v-model="accountForm.userRiskType" autocomplete="off" placeholder="账户风险类型"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调仓建议" :label-width="formLabelWidth" prop="hasAdvice">
              <el-radio-group v-model="accountForm.hasAdvice">
                <el-radio-button :label=true>有建议</el-radio-button>
                <el-radio-button :label=false>无建议</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="6">
          <el-col :span="8">
            <el-form-item label="Account ID" :label-width="formLabelWidth" prop="accountId">
              <el-input v-model="accountForm.accountId" autocomplete="off" placeholder="请输入投资子账户ID,多组合则有多个"
                        type="textarea"  rows="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="Portfolio ID" :label-width="formLabelWidth" prop="portfolioId">
              <el-input v-model="accountForm.portfolioId" autocomplete="off" placeholder="请输入持仓组合ID,多组合则有多个"
                        type="textarea" rows="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="持仓组合" :label-width="formLabelWidth" prop="holdings">
              <el-input v-model="accountForm.holdings" autocomplete="off" placeholder="持仓组合"
                        type="textarea"  rows="1"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="6">
          <el-col :span="10">
            <el-form-item label="账号操作记录" :label-width="formLabelWidth" prop="operateRecord">
              <el-input v-model="accountForm.operateRecord" autocomplete="off" placeholder="账号操作记录"
                        type="textarea" rows="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
              <el-input v-model="accountForm.remark" autocomplete="off" placeholder="备注"
                        type="textarea" rows="1"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row v-if="operate === 'add' && ! select">
        <el-col :span="8">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            accetpt=".xlsx,.xls"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="handleOnChange"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :auto-upload="false"
            multiple
            :limit="1"
            :file-list="fileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">温馨提示：只能上传excel文件，请按照
              <a href='/static/raas-test-account-template.xlsx' style="color: green; font-size: 16px"
                 download="raas-test-account-template.xlsx"> 模板 </a>填写...</div>
          </el-upload>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="small"  @click="handleCancel"> 取 消 </el-button>
        <!--        "dialogFormVisible = false"-->
        <el-button  size="small"  type="primary" :loading="uploading"  @click="handleOK"> 确 定 </el-button>
      </div>
    </el-dialog>
  </span>
</template>

<script>
import {raas_add_account, raas_edit_account, raas_import_account} from "@/api/account";
import getQueryString from "@/utils/getCookies";
const getCookies = getQueryString.getCookie;
export default {
  name: "DataModal",
  props: {
    operate: {
      type: String,
      default: 'edit'
    },
    title: {
      type: String,
      default: ''
    },
    parQuery: {
      type: Object,
      default: () => {}
    },
    flagSelect: {
      type: Object,
      default: () => {}
    },
    pageNum: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      fd: '',
      radio: '1',
      select: true,
      uploading: false,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      envOption:  [{
        value: 'SIT环境',
        label: 'SIT'
      }, {
        value: '开发环境',
        label: 'DEV'
      }, {
        value: '生产环境',
        label: 'PROD'
      }],
      accountForm: {
        project: '',
        env: '',
        userName: '',
        phone: '',
        email: '',
        loginPassword: '',
        transPassword: '',
        verifyCode: '',
        clientId: '',
        flagUsage: false,
        isHold: false,
        raasUid: '',
        accountId: '',
        portfolioId: '',
        userRiskType: '',
        holdings: '',
        hasAdvice: 'No',
        operateRecord: '',
        remark: ''
      },
      rulesAccountForm: {
        project: [
          { required: true, message: '请输入项目名称', trigger: 'blur' },
        ],
        env: [
          { required: true, message: '请选择/输入环境名', trigger: 'blur' }
        ]
      },
      accountId: 0,
    }
  },
  methods: {
    getUserName() {
      return getCookies('username')
    },
    showDialog: function (index=0, row={}){
      this.dialogFormVisible = true
      if (this.operate === 'edit') {
        this.accountId = row.id
        this.accountForm = row
        this.accountForm.flagUsage = row.flagUsage? row.flagUsage === '是': undefined
        this.accountForm.isHold = row.isHold? row.isHold === '是': undefined
        this.accountForm.hasAdvice = row.hasAdvice? row.hasAdvice === '是': undefined
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleOnChange(file, fileList) {
      this.fileList = [file];
      let fd = new FormData();
      fd.append("file", file.raw);
      this.fd = fd;
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    beforeUpload(file) {
      // 文件大小限制为100M
      const fileLimit = file.size / 1024 / 1024 < 100;
      if (!fileLimit) {
        this.$message.error("上传文件大小不超过100M！");
      }
      return false;
    },
    handleCancel() {
      if(this.operate === 'add' && ! this.select ) {
        this.fileList = []; // 清空选择的文件列表
      } else if(this.operate === 'edit') {
        this.accountForm.flagUsage = this.accountForm.flagUsage === true? '是': '否'
        this.accountForm.isHold = this.accountForm.isHold === true? '是': '否'
      }
      this.dialogFormVisible = false
    },
    handleOK() {
      if (this.operate === 'add' && this.select) {  // 添加一条记录
        this.$refs.accountForm.validate((valid) => {
          if (valid) {
            console.log('往服务器添加一条记录')
            this.handleAddAccount(this.accountForm)
          }
        })
      } else if (this.operate === 'add' && ! this.select) {  // 导入账号
        console.log('导入测试账号')
        this.handleImportAccount()
      } else if (this.operate === 'edit') {  // 编辑测试账号
        this.handleEditAccount(this.accountForm)
        this.parQuery.project = (this.flagSelect.proj === 'all' || this.flagSelect.proj === '') ? '' : this.accountForm.project
        this.flagSelect.proj = this.parQuery.project === '' ? '' : this.parQuery.project
        this.parQuery.pageNum = this.pageNum ? this.pageNum : 1
      }
      console.log('查询选择项：',this.flagSelect)
      this.$emit('listAccount', this.parQuery)
      this.dialogFormVisible = false
    },
    handleAddAccount(accForm) {
      let  params = {
        creator: this.getUserName(),
        flagUsage: accForm.flagUsage? (accForm.flagUsage === true ? 1: 0): 0,
        isHold: accForm.isHold? (accForm.isHold === true ? 1: 0): 0,
        project: accForm.project,
        env: accForm.env,
        userName: accForm.userName,
        phone: accForm.phone,
        email: accForm.email,
        loginPassword: accForm.loginPassword,
        transPassword: accForm.transPassword,
        verifyCode: accForm.verifyCode,
        clientId: accForm.clientId,
        raasUid: accForm.raasUid,
        accountId: accForm.accountId,
        portfolioId: accForm.portfolioId,
        userRiskType: accForm.userRiskType,
        holdings: accForm.holdings,
        hasAdvice: accForm.hasAdvice? (accForm.hasAdvice === true ? 1: 0): 0,
        operateRecord: accForm.operateRecord,
        remark: accForm.remark
      }
      raas_add_account(params).then( res => {
        if(res.code === 200) {
          this.$message({
            type: 'success',
            message: '新增账号成功'
          });
        }
      })
    },
    handleImportAccount() {
      let accountFile = this.fd !=='' ? this.fd.get('file'): ''
      let params = new FormData()
      params.append('file', accountFile)
      params.append('creator', getCookies('username'));
      console.log(params.get('file'))
      raas_import_account(params).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '导入账号成功'
          });
        }
      })
    },
    handleEditAccount(accForm) {
      let params = {
        id: this.accountId,
        modifier: this.getUserName(),
        flagUsage: accForm.flagUsage? (accForm.flagUsage === true ? 1: 0): 0,
        isHold: accForm.isHold? (accForm.isHold === true ? 1: 0): 0,
        project: accForm.project,
        env: accForm.env,
        userName: accForm.userName,
        phone: accForm.phone,
        email: accForm.email,
        loginPassword: accForm.loginPassword,
        transPassword: accForm.transPassword,
        verifyCode: accForm.verifyCode,
        clientId: accForm.clientId,
        raasUid: accForm.raasUid,
        accountId: accForm.accountId,
        portfolioId: accForm.portfolioId,
        userRiskType: accForm.userRiskType,
        holdings: accForm.holdings,
        hasAdvice: accForm.hasAdvice? (accForm.hasAdvice === true ? 1: 0): 0,
        operateRecord: accForm.operateRecord,
        remark: accForm.remark
      }
      raas_edit_account(params).then( res => {
        console.log(res)
        if(res.code === 200) {
          let data = res.data? res.data: 0
          if(data > 0) {
            this.$message({
              type: 'success',
              message: '编辑账号成功'
            });
          }
        }
      })
    },
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px
}
</style>
